/**
 * 
 */
package cen5501c.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Jiangyan Xu
 *
 */
public class Server {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int server_port = 22112;
		if (args.length > 0) {
			try {
				server_port = Integer.parseInt(args[0]);
			} catch (NumberFormatException e) {
				//Just use the default value of server_port
			}
		} else {
			System.out.println("Use default port 22112. Alternatively, specify another port as the 1st argument");
		}

		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(server_port);
		} catch (IOException e) {
			System.err.println("Unable to start server, change port/check network and retry");
			return;
		}

		while (true) {
			Socket connectionSocket = null;
			try {
				connectionSocket = serverSocket.accept();
				System.out.println("Received an incoming connection from " + connectionSocket.getRemoteSocketAddress());
				Thread t = new Thread(new ServerWorker(connectionSocket));
				t.start();
			} catch (IOException e) {
				return;
			}

		}
	}
}
